'use client';

import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState,
} from 'react';
import { useGlobalState } from '@/hooks';
import Link from 'next/link';
import { NextPage } from 'next';
import FontIcon from '../FontIcon';
import './CategoriesMenuMobile.scss';

const rootId = Number(process.env.NEXT_PUBLIC_ROOT_CATEGORY_ID);

const getCategoryLink = (curCate: Category, categories: Category[]) => {
  return '/categories/' + curCate.format_paths;
};

const getChildrenOf = (curCate: Category, categories: ViewCategory[]) => {
  return categories.filter(c => c.parent_id == curCate.category_id);
};

type ViewCategory = Category & {
  link: string;
  isOpen: boolean;
  children: ViewCategory[];
};
type Props = {
  visible: boolean;
  setVisible: React.Dispatch<React.SetStateAction<boolean>>;
};
const CategoriesMenuMobile = forwardRef(function CategoriesMenuMobileCmp(
  { visible = false, setVisible }: Props,
  ref: React.Ref<{ resetState: Fn }>
) {
  const categoriesData = useGlobalState('product', 'categoryList');
  const [openingCategoryMap, setOpeningCategoryMap] = useState<
    Record<number, boolean>
  >({});
  const { level1CateList, categories } = useMemo(() => {
    const categories: ViewCategory[] = categoriesData.map(cate => {
      return {
        ...cate,
        link: getCategoryLink(cate, categoriesData),
        children: [],
        isOpen: openingCategoryMap[cate.category_id] || false,
      };
    });

    categories.forEach(cate => {
      cate.children = getChildrenOf(cate, categories);
    });

    const level1List = categories.filter(d => d.parent_id == rootId);
    return {
      level1CateList: level1List,
      categories,
    };
  }, [categoriesData, openingCategoryMap]);

  const [activeLevel1Cate, setActiveLevel1Cate] = useState<null | ViewCategory>(
    null
  );
  const activeL1Ref = useRef(activeLevel1Cate);
  const updateActiveLevel1Cate = (cate: ViewCategory) => {
    setActiveLevel1Cate(cate);
    activeL1Ref.current = cate;
  };
  useEffect(() => {
    if (activeL1Ref.current) {
      const newActiveCate = level1CateList.find(
        cate => cate.category_id === activeL1Ref.current?.category_id
      );
      setActiveLevel1Cate(newActiveCate!);
    }
  }, [level1CateList]);

  const resetState = () => {
    setActiveLevel1Cate(null);
    activeL1Ref.current = null;
    setOpeningCategoryMap({});
  };

  useImperativeHandle(ref, () => {
    return {
      resetState,
    };
  });

  const toggleOpenCategory = (cate: ViewCategory) => {
    setOpeningCategoryMap(prev => {
      return {
        ...prev,
        [cate.category_id]: !cate.isOpen,
      };
    });
  };
  const goBack = () => {
    if (activeLevel1Cate) {
      setActiveLevel1Cate(null);
      return;
    }
    setVisible(false);
  };

  return (
    <div className={`category-menu-mobile ${visible ? 'animate' : 'hide'}`}>
      <div className="category-menu-inner h100p flex-col">
        <div className="category-menu-hd pb15 flex-row items-center">
          <div className="arrow-area cursor-pointer" onClick={goBack}>
            <FontIcon
              name="direction-left"
              size={18}
              style={{ color: 'black' }}
            />
          </div>
          <h2 className="title flex-1 ta-c">Categories</h2>
        </div>
        <div className="category-menu-main flex-1 overflow-auto thin-scroll-bar">
          {/* level1-list */}
          <div
            className={`category-level1-list cate-list ${activeLevel1Cate ? 'hide' : ''}`}
          >
            {level1CateList.map((cate: ViewCategory, index: number) => (
              <li
                key={index}
                className={'category-item'}
                onClick={() => updateActiveLevel1Cate(cate)}
              >
                <div
                  data-href={cate.link}
                  className="flex-row items-center justify-between"
                >
                  {cate.title}
                  <FontIcon name="forward-line" size={18} />
                </div>
              </li>
            ))}
          </div>
          {/* level2-list */}
          <div
            className={`category-level2-outer ${activeLevel1Cate ? '' : 'hide'}`}
          >
            <div className="category-level2">
              {/* all-item */}
              <div className="category-level2-all category-item-all">
                <Link href={activeLevel1Cate?.link || ''}>
                  Shop All {activeLevel1Cate?.title}
                </Link>
              </div>
              {/* list */}
              <ul className="category-level2-list cate-list">
                {activeLevel1Cate?.children?.map(
                  (cate2: ViewCategory, index: number) => (
                    <li
                      className={`category-level2-item category-item ${cate2.isOpen ? 'open' : ''}`}
                      key={index}
                    >
                      <div
                        className="title-line flex-row items-center justify-between"
                        onClick={() => toggleOpenCategory(cate2)}
                      >
                        <div className="text">{cate2.title}</div>
                        <div
                          className={`icon-area ${cate2.isOpen ? 'reverse-y' : ''}`}
                        >
                          <FontIcon name="expand-line" size={18} />
                        </div>
                      </div>
                      <ul
                        className={`category-level3-list cate-list collapsible ${cate2.isOpen ? 'open' : ''}`}
                      >
                        <li
                          className="category-level3-all category-item-all"
                          key={'all'}
                        >
                          <Link href={cate2.link || ''}>
                            Shop all {cate2.title}
                          </Link>
                        </li>
                        {cate2.children?.map(
                          (cate3: ViewCategory, idx3: number) => {
                            return (
                              <li
                                className="category-level3-item category-item"
                                key={idx3}
                              >
                                <Link href={cate3.link || ''}>
                                  {cate3.title}
                                </Link>
                              </li>
                            );
                          }
                        )}
                      </ul>
                    </li>
                  )
                )}
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
});

export default CategoriesMenuMobile;
